<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form" @submit.prevent>
      <el-form-item label="用户名:">
        <el-input
          placeholder="请输入要搜索的用户名"
          v-model="keyWord"
          @keyup.enter="search"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!keyWord" @click="search">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" @click="addUser">添加用户</el-button>
    <el-button
      type="danger"
      :disabled="!selectIdArr.length"
      @click="deleteSelectUser"
    >
      批量删除
    </el-button>
    <!-- table展示用户信息 -->
    <el-table
      @selection-change="selectChange"
      style="margin: 10px 0"
      border
      :data="userArr"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="80px"
      ></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #default="{ row }">
          <el-button
            type="success"
            size="small"
            @click="setRole(row)"
            icon="User"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            @click="deleteUser(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '编辑用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form
        :model="userParams"
        status-icon
        :rules="rules"
        size="large"
        ref="formRef"
      >
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请输入姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请输入昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请输入密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-drawer>
  <!-- 抽屉：用户某一个已有的账号进行职位分配 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配用户职位</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            style="margin-right: 30px"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <!-- 显示职位的复选框 -->
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="index"
              :label="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="drawer1 = false">取消</el-button>
      <el-button type="primary" @click="confirmClick">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser,
} from '@/api/acl/user'
import type {
  UserResponseData,
  Records,
  User,
  AllRole,
  AllRoleResponseData,
  SetRoleData,
} from '@/api/acl/user/type'
import useLayOutSettingStore from '@/store/modules/setting'

// 默认页码
const pageNo = ref(1)
// 每页展示的数据
const pageSize = ref(5)
// 用户总个数
const total = ref(0)
// 存储全部用户信息
const userArr = ref<Records>([])
// 定义响应式数据控制抽屉的显示与隐藏
const drawer = ref(false)
// 控制分配角色抽屉的显示与隐藏
const drawer1 = ref(false)
// 收集用户信息的响应式数据
const userParams = ref<User>({
  username: '',
  name: '',
  password: '',
})
// 获取form组件实例
const formRef = ref()
// 全选复选框收集数据：是否全选
const checkAll = ref(false)
// 全部用户职位数据
const allRole = ref<AllRole>([])
// 用户已有职位数据
const userRole = ref<AllRole>([])
// 存储批量删除的用户ID
const selectIdArr = ref<User[]>([])
// 收集用户输入的关键字
const keyWord = ref('')
// 获取setting仓库
const settingStore = useLayOutSettingStore()

// 全选复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
}

// 全部复选框的change事件
const handleCheckCitiesChange = (val: string[]) => {
  // 已勾选的项目的长度
  const checkedCount = val.length
  checkAll.value = checkedCount === allRole.value.length
}

// 获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  // 收集当前页码
  pageNo.value = pager
  const res: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyWord.value,
  )
  if (res.code === 200) {
    total.value = res.data.total
    userArr.value = res.data.records
  }
}
getHasUser()

// 分页器下拉菜单的自定义事件的回调
const handler = () => {
  getHasUser()
}

// 添加用户按钮的回调
const addUser = () => {
  // 数据清空
  Object.assign(userParams.value, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })

  // 清除上一次的错误提升信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
  // 显示抽屉
  drawer.value = true
}

// 更新已有用户按钮的回调
const updateUser = (row: User) => {
  // 存储收集已有的账号信息
  Object.assign(userParams.value, row)
  // 清除上一次的错误提升信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
  // 抽屉显示
  drawer.value = true
}

// 保存按钮的回调
const save = async () => {
  // 表单校验
  await formRef.value.validate()
  // 保存按钮：添加新的用户 | 更新已有的用户账号信息
  const res: any = await reqAddOrUpdateUser(userParams.value)
  // 添加或更改成功
  if (res.code === 200) {
    // 关闭抽屉
    drawer.value = false
    // 添加成功提升信息
    ElMessage.success(userParams.value.id ? '更新成功' : '添加成功')
    // 页面刷新
    getHasUser(userParams.value.id ? pageNo.value : 1)
    // 页面刷新
    window.location.reload()
  } else {
    // 关闭抽屉
    drawer.value = false
    // 添加失败的提升信息
    ElMessage.error(userParams.value.id ? '更新失败' : '添加失败')
  }
}

// 取消按钮的回调
const cancel = () => {
  // 关闭抽屉
  drawer.value = false
}

// 分配角色按钮的回调
const setRole = async (row: User) => {
  // 保存数据
  Object.assign(userParams.value, row)
  // 获取全部职位的数据与用户已有的职位数据
  const res: AllRoleResponseData = await reqAllRole(
    userParams.value.id as number,
  )
  if (res.code === 200) {
    // 存储数据
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
    // 开启抽屉
    drawer1.value = true
  } else {
    // 提示信息
    ElMessage.error('获取用户职位失败')
  }
}

// drawer1保存按钮的回调
const confirmClick = async () => {
  // 收集数据
  const data: SetRoleData = {
    userId: userParams.value.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  }
  const res: any = await reqSetUserRole(data)
  if (res.code === 200) {
    ElMessage.success('分配职位成功')
    // 关闭抽屉
    drawer1.value = false
    // 页面刷新
    getHasUser(pageNo.value)
  }
}

// 删除用户的回调
const deleteUser = async (userId: number) => {
  const res: any = await reqRemoveUser(userId)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage.error('系统数据不能删除')
  }
}

// table复选框勾选触发的回调
const selectChange = (val: any) => {
  selectIdArr.value = val
}

// 批量删除按钮的回调
const deleteSelectUser = async () => {
  // 整理批量删除的参数
  const idsList: any = selectIdArr.value.map((item) => item.id)
  const res: any = await reqSelectUser(idsList)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getHasUser(
      userArr.value.length > idsList.length ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage.error('系统数据不能删除')
  }
}

// 搜索按钮的回调
const search = () => {
  // 判断keyword是否为空
  if (!keyWord.value) return
  // 根据关键字获取相应的用户数据
  getHasUser()
  // 清空关键字
  keyWord.value = ''
}

// 重置按钮的回调
const reset = () => {
  // 刷新页面
  settingStore.refsh()
}

// 表单校验的规则对象
const rules = {
  username: [
    {
      required: true,
      trigger: blur,
      validator: (rule: any, value: any, callBack: any) => {
        // 用户名字，昵称长度至少5位
        if (value.trim().length >= 5) {
          callBack()
        } else {
          callBack(new Error('用户名至少5位'))
        }
      },
    },
  ],
  name: [
    {
      required: true,
      trigger: blur,
      validator: (rule: any, value: any, callBack: any) => {
        // 用户名字，昵称长度至少5位
        if (value.trim().length >= 5) {
          callBack()
        } else {
          callBack(new Error('昵称至少5位'))
        }
      },
    },
  ],
  password: [
    {
      required: true,
      trigger: blur,
      validator: (rule: any, value: any, callBack: any) => {
        // 密码长度至少5位
        if (value.trim().length >= 6) {
          callBack()
        } else {
          callBack(new Error('密码至少6位'))
        }
      },
    },
  ],
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
